import {
	getCurrentUserMenuList
} from '@/api/sys/menu'
import router from '@/router'

function setChildren(route, children) {
	if (children) {
		let childrenRoutes = [];
		children.forEach(menu => {
			let childRoute = {
				path: menu.path,
				name: menu.path,
				meta: {
					isNew: true
				}
			}
			menu.route = route.path + '/' + menu.path
			if(menu.component) {
				childRoute.component = (resolve) => require(['@/views/' + menu.component], resolve);
			}
			childrenRoutes.push(childRoute)
			if (menu.children) {
				setChildren(childRoute, menu.children)
			}
		})
		route.children = childrenRoutes;
	}
}

const menu = {
	state: {
		menuList: []
	},

	mutations: {
		setMenuList: (state, menuList) => {
			state.menuList = menuList
		}
	},

	actions: {
		clearMenuList({
			commit
		}) {
			commit('setMenuList', [])
		},
		// 登录
		setMenuList({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getCurrentUserMenuList().then(res => {
					let rows = res;
					if (!rows || rows.length == 0) {
						return reject('获取菜单数据异常！')
					}
					let results = [];
					// 设置子节点到父节点的children数组中
					rows.forEach(row => {
						// 寻找row上级行
						let parent = rows.find(r => r.menuId == row.parentId);
						if (!parent) {
							results.push(row);
							return;
						}
						if (!parent.children) { // 如果parent没有children属性，则设置
							parent.children = []
						}
						parent.children.push(row);
					})
					commit('setMenuList', results)
					let routes = [];
					results.forEach(row => {
						let route = {
							path: '/' + row.path,
							name: row.path,
							component: (resolve) => require(['@/views/' + (row.component? row.component : 'home')], resolve)
						}
						setChildren(route, row.children)
						routes.push(route)
					})
					routes.forEach(route => {
						router.options.routes.push(route);
						router.addRoute(route)
					})
					console.log('routes', routes, router.getRoutes())
					// router.addRoutes(routes)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

export default menu
